import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    // 创建 controller
    let controller:FlutterViewController = window?.rootViewController as! FlutterViewController
    //创建通道
    let batterChannel = FlutterMethodChannel(
      name:"samples.flutter.dev/battery",
      binaryMessenger: controller.binaryMessenger
    );
    // 添加通道钩子函数
    batterChannel.setMethodCallHandler({
      [weak self] (call: FlutterMethodCall, result: FlutterResult) -> Void in
      // Note: this method is invoked on the UI thread.
      guard (call.method == "getBatteryLevel") else {
        result(FlutterMethodNotImplemented)
        return
      }
      self?.receiveBatteryLevel(result: result)
    })
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
  
  // 钩子函数实现
  private func receiveBatteryLevel(result: FlutterResult) {
    let device = UIDevice.current
    device.isBatteryMonitoringEnabled = true
    if (device.batteryState == UIDevice.BatteryState.unknown) {
      result(Int(2 * 100))
      // result(FlutterError(code: "UNAVAILABLE", message: "Battery info unavailable", details: nil))
    } else {
      result(Int(device.batteryLevel * 100))
    }
  }
  
}
